<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频播放 - 局域网视频学习系统</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .player-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .player-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .breadcrumb {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 16px;
            font-size: 14px;
            color: #666;
        }

        .breadcrumb a {
            color: var(--primary-color);
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .video-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .video-meta {
            display: flex;
            align-items: center;
            gap: 20px;
            font-size: 14px;
            color: #666;
        }

        .video-actions {
            display: flex;
            gap: 10px;
            margin-left: auto;
        }

        .action-btn {
            background: none;
            border: 1px solid var(--border-color);
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .action-btn:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .action-btn.favorited {
            background: #ff6b6b;
            border-color: #ff6b6b;
            color: white;
        }

        .player-layout {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
        }

        .video-section {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .video-player {
            width: 100%;
            height: 500px;
            background: #000;
            position: relative;
        }

        .video-player video {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .video-controls {
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .progress-section {
            margin-bottom: 16px;
        }

        .progress-label {
            font-size: 14px;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            cursor: pointer;
        }

        .progress-fill {
            height: 100%;
            background: var(--primary-color);
            transition: width 0.3s ease;
            width: 0%;
        }

        .progress-time {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }

        .video-info {
            padding: 20px;
        }

        .video-description {
            font-size: 14px;
            line-height: 1.6;
            color: var(--neutral-dark);
            margin-bottom: 16px;
        }

        .video-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .tag {
            background: rgba(46, 134, 171, 0.1);
            color: var(--primary-color);
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
        }

        .sidebar {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .playlist-section {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .playlist-header {
            padding: 16px 20px;
            background: var(--neutral-light);
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .playlist-item {
            padding: 12px 20px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: background 0.3s ease;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .playlist-item:hover {
            background: #f8f9fa;
        }

        .playlist-item.active {
            background: rgba(255, 230, 109, 0.2);
            border-left: 4px solid var(--student-color);
        }

        .playlist-item.playing {
            background: rgba(46, 134, 171, 0.1);
            border-left: 4px solid var(--primary-color);
        }

        .playlist-item.watched {
            opacity: 0.7;
        }

        .playlist-item.watched .playlist-info h4::after {
            content: " ✓";
            color: #4caf50;
            font-weight: bold;
        }

        .playlist-item:last-child {
            border-bottom: none;
        }

        .playlist-thumbnail {
            width: 60px;
            height: 40px;
            background: #f0f0f0;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 16px;
            flex-shrink: 0;
        }

        .playlist-info h4 {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--neutral-dark);
            line-height: 1.3;
        }

        .playlist-meta {
            font-size: 12px;
            color: #666;
        }

        .playlist-duration {
            font-size: 12px;
            color: #999;
            margin-left: auto;
        }

        .playlist-progress {
            width: 100%;
            height: 3px;
            background: #e0e0e0;
            border-radius: 2px;
            margin-top: 8px;
            overflow: hidden;
        }

        .playlist-progress-bar {
            height: 100%;
            background: var(--primary-color);
            border-radius: 2px;
            transition: width 0.3s ease;
        }

        .playlist-stats {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 4px;
            font-size: 11px;
            color: #999;
        }

        .playlist-watch-time {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 3px;
        }

        .notes-section {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .notes-header {
            padding: 16px 20px;
            background: var(--neutral-light);
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .notes-content {
            padding: 20px;
        }

        .note-input {
            width: 100%;
            min-height: 80px;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-size: 14px;
            resize: vertical;
            margin-bottom: 12px;
        }

        .note-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(46, 134, 171, 0.2);
        }

        .note-save-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .note-save-btn:hover {
            background: #1e5f7a;
        }

        .notes-list {
            margin-top: 20px;
        }

        .note-item {
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            margin-bottom: 12px;
            background: #f8f9fa;
        }

        .note-time {
            font-size: 12px;
            color: #666;
            margin-bottom: 6px;
        }

        .note-content {
            font-size: 14px;
            line-height: 1.5;
            color: var(--neutral-dark);
        }

        .note-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .note-actions {
            display: flex;
            gap: 8px;
        }

        .note-edit-btn, .note-delete-btn {
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .note-edit-btn {
            background: #e3f2fd;
            color: #1976d2;
        }

        .note-edit-btn:hover {
            background: #bbdefb;
        }

        .note-delete-btn {
            background: #ffebee;
            color: #d32f2f;
        }

        .note-delete-btn:hover {
            background: #ffcdd2;
        }

        .note-title {
            font-weight: 600;
            margin-bottom: 6px;
            color: var(--neutral-dark);
        }

        .note-position {
            font-size: 12px;
            color: #666;
            margin-top: 6px;
            font-style: italic;
        }

        .no-notes {
            text-align: center;
            color: #999;
            font-style: italic;
            padding: 20px;
        }

        .favorited {
            background: #ff6b6b !important;
            color: white !important;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error-message {
            text-align: center;
            padding: 40px;
            color: var(--error-color);
        }

        @media (max-width: 1024px) {
            .player-layout {
                grid-template-columns: 1fr;
            }
            
            .video-player {
                height: 300px;
            }
        }

        @media (max-width: 768px) {
            .video-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .video-actions {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <a href="index.html" class="navbar-brand">
                    📚 局域网视频学习系统
                </a>
                <div style="display: flex; align-items: center; gap: 20px;">
                    <a href="index.html" style="color: var(--neutral-dark); text-decoration: none;">
                        🏠 首页
                    </a>
                    <a href="favorites.html" style="color: var(--neutral-dark); text-decoration: none;">
                        ❤️ 我的收藏
                    </a>
                    <a href="playlists.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📋 播放列表
                    </a>
                    <a href="exams.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📝 考试中心
                    </a>
                    <a href="profile.html" style="color: var(--neutral-dark); text-decoration: none;">
                        👤 个人资料
                    </a>
                    <span style="color: var(--neutral-dark);">
                        <span data-user-name>学生</span>
                    </span>
                    <button onclick="logout()" class="logout-btn">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="content-wrapper">
        <div class="player-container">
            <!-- 视频标题区域 -->
            <div class="player-header">
                <div class="breadcrumb">
                    <a href="index.html">首页</a>
                    <span>›</span>
                    <span id="breadcrumbCategory">视频</span>
                    <span>›</span>
                    <span id="videoTitle">视频标题</span>
                </div>
                <h1 class="video-title" id="videoTitleText">视频标题</h1>
                <div class="video-meta">
                    <span>上传者: <span id="uploaderName">未知老师</span></span>
                    <span>上传时间: <span id="uploadTime">-</span></span>
                    <span>观看次数: <span id="viewCount">0</span></span>
                    <div class="video-actions">
                        <button class="action-btn" id="favoriteBtn" onclick="toggleFavorite()">
                            ❤️ 收藏
                        </button>
                        <button class="action-btn" onclick="addToPlaylist()">
                            📋 添加到播放列表
                        </button>
                        <button class="action-btn" onclick="shareVideo()">
                            🔗 分享
                        </button>
                    </div>
                </div>
            </div>

            <!-- 播放器布局 -->
            <div class="player-layout">
                <!-- 视频播放区域 -->
                <div class="video-section">
                    <div class="video-player" id="videoPlayer">
                        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666;">
                            <div class="loading-wave" style="margin-bottom: 16px;"></div>
                            <p style="font-size: 14px;">正在加载视频...</p>
                        </div>
                    </div>
                    <div class="video-controls">
                        <div class="progress-section">
                            <div class="progress-label">播放进度</div>
                            <div class="progress-bar" id="progressBar" onclick="seekTo(event)">
                                <div class="progress-fill" id="progressFill"></div>
                            </div>
                            <div class="progress-time">
                                <span id="currentTime">00:00</span>
                                <span id="totalTime">00:00</span>
                            </div>
                        </div>
                    </div>
                    <div class="video-info">
                        <div class="video-description" id="videoDescription">
                            视频简介将在这里显示...
                        </div>
                        <div class="video-tags" id="videoTags">
                            <!-- 标签将在这里生成 -->
                        </div>
                    </div>
                </div>

                <!-- 侧边栏 -->
                <div class="sidebar">
                    <!-- 播放列表 -->
                    <div class="playlist-section">
                        <div class="playlist-header">
                            相关视频
                        </div>
                        <div id="playlistContent">
                            <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #666;">
                                <div class="loading-pulse" style="margin-bottom: 12px;"></div>
                                <p style="font-size: 12px;">加载相关视频...</p>
                            </div>
                        </div>
                    </div>

                    <!-- 学习笔记 -->
                    <div class="notes-section">
                        <div class="notes-header">
                            我的笔记
                        </div>
                        <div class="notes-content">
                            <textarea class="note-input" id="noteInput" placeholder="记录当前视频的知识点..."></textarea>
                            <button class="note-save-btn" onclick="saveNote()">保存笔记</button>
                            <div class="notes-list" id="notesList">
                                <!-- 笔记列表将在这里生成 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentVideo = null;
        let videoPlayer = null;
        let currentTime = 0;
        let totalTime = 0;
        let isPlaying = false;
        let isFavorited = false;
        let watchStartTime = null;
        let totalWatchDuration = 0;
        let learningRecord = null;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 获取视频ID
            const videoId = Utils.getUrlParam('id');
            if (!videoId) {
                showError('视频ID不存在');
                return;
            }

            // 加载视频数据
            loadVideo(videoId);
        });

        // 加载视频数据
        async function loadVideo(videoId) {
            try {
                const response = await API.get(`/video/${videoId}`);
                if (response.success) {
                    currentVideo = response.video;
                    renderVideo();
                    loadRelatedVideos();
                    loadNotes();
                    checkFavoriteStatus();
                    loadLearningRecord();
                } else {
                    showError('视频不存在或已被删除');
                }
            } catch (error) {
                console.error('加载视频失败:', error);
                showError('加载视频失败，请稍后重试');
            }
        }

        // 渲染视频
        function renderVideo() {
            if (!currentVideo) return;

            // 更新页面标题
            document.title = currentVideo.title + ' - 局域网视频学习系统';
            document.getElementById('videoTitleText').textContent = currentVideo.title;
            document.getElementById('uploaderName').textContent = currentVideo.uploaderName || '未知老师';
            document.getElementById('uploadTime').textContent = Utils.formatTime(currentVideo.uploadTime);
            document.getElementById('viewCount').textContent = currentVideo.viewCount || 0;
            document.getElementById('videoDescription').textContent = currentVideo.intro || '暂无简介';

            // 渲染标签
            const tagsContainer = document.getElementById('videoTags');
            if (currentVideo.tags) {
                const tags = currentVideo.tags.split(',').map(tag => tag.trim());
                tagsContainer.innerHTML = tags.map(tag => `<span class="tag">${tag}</span>`).join('');
            } else {
                tagsContainer.innerHTML = '';
            }

            // 创建视频播放器
            createVideoPlayer();
        }

        // 创建视频播放器
        function createVideoPlayer() {
            const playerContainer = document.getElementById('videoPlayer');
            
            // 检查用户权限和视频状态
            const user = UserManager.getCurrentUser();
            const userRole = UserManager.getUserRole();
            const userId = UserManager.getUserId();
            const isAdmin = userRole === 0;
            const isTeacher = userRole === 1;
            const isStudent = userRole === 2;
            const isLoggedIn = UserManager.isLoggedIn();
            
            console.log('用户信息:', { user, userRole, userId, isLoggedIn });
            console.log('视频信息:', { id: currentVideo.id, status: currentVideo.status, uploaderId: currentVideo.uploaderId });
            
            // 权限检查逻辑
            if (isAdmin) {
                // 管理员可以访问所有视频
                console.log('管理员访问视频，无限制');
            } else if (isTeacher) {
                // 老师可以访问自己发布的视频或已审核通过的视频
                if (currentVideo.status !== 1 && currentVideo.uploaderId !== userId) {
                    console.log('老师权限检查失败:', { status: currentVideo.status, uploaderId: currentVideo.uploaderId, userId });
                    playerContainer.innerHTML = `
                        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666;">
                            <i style="font-size: 48px; margin-bottom: 16px;">🚫</i>
                            <h3>视频暂不可播放</h3>
                            <p>只能访问自己的视频或已审核通过的视频</p>
                        </div>
                    `;
                    return;
                }
            } else if (isStudent) {
                // 学生只能访问已审核通过的视频
                if (currentVideo.status !== 1) {
                    console.log('学生权限检查失败:', { status: currentVideo.status });
                    playerContainer.innerHTML = `
                        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666;">
                            <i style="font-size: 48px; margin-bottom: 16px;">🚫</i>
                            <h3>视频暂不可播放</h3>
                            <p>视频审核未通过，请等待审核</p>
                        </div>
                    `;
                    return;
                }
            } else {
                // 未登录用户不能访问任何视频
                console.log('未登录用户权限检查失败');
                playerContainer.innerHTML = `
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666;">
                        <i style="font-size: 48px; margin-bottom: 16px;">🔒</i>
                        <h3>请先登录</h3>
                        <p>只有登录用户才能观看视频</p>
                        <button onclick="window.location.href='../login.html'" style="margin-top: 20px; padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
                            立即登录
                        </button>
                    </div>
                `;
                return;
            }
            
            // 如果是未审核或已拒绝的视频，显示提示信息
            if (currentVideo.status !== 1) {
                const statusMessage = currentVideo.status === 0 ? '视频正在审核中' : 
                                    currentVideo.status === 2 ? '视频审核未通过' : '视频状态异常';
                const statusColor = currentVideo.status === 0 ? '#ff9800' : '#f44336';
                
                playerContainer.innerHTML = `
                    <div style="position: relative; width: 100%; height: 100%;">
                        <div style="position: absolute; top: 10px; left: 10px; background: ${statusColor}; color: white; padding: 8px 12px; border-radius: 4px; font-size: 12px; z-index: 10;">
                            ${statusMessage}
                        </div>
                        <div id="videoPlayerContent" style="width: 100%; height: 100%;"></div>
                    </div>
                `;
                playerContainer = document.getElementById('videoPlayerContent');
            }
            
            // 创建video元素
            const video = document.createElement('video');
            video.controls = true;
            video.preload = 'metadata';
            
            // 构建视频路径
            const streamPath = '/api/video/stream/' + currentVideo.id;
            
            console.log('视频路径信息:', {
                id: currentVideo.id,
                path: currentVideo.path,
                streamPath: streamPath,
                fullVideoInfo: currentVideo
            });
            
            // 测试流媒体路径是否可访问
            fetch(streamPath, { method: 'HEAD' })
                .then(response => {
                    console.log('流媒体路径测试结果:', {
                        url: streamPath,
                        status: response.status,
                        statusText: response.statusText,
                        headers: Object.fromEntries(response.headers.entries())
                    });
                })
                .catch(error => {
                    console.error('流媒体路径测试失败:', error);
                });
            
            // 直接使用流媒体API作为视频源
            video.src = streamPath;
            
            // 设置样式
            video.style.width = '100%';
            video.style.height = '100%';
            video.style.objectFit = 'contain';
            
            // 清空容器并添加视频
            playerContainer.innerHTML = '';
            playerContainer.appendChild(video);
            
            videoPlayer = video;
            
            // 绑定事件
            video.addEventListener('loadedmetadata', function() {
                totalTime = 0; // 视频时长暂时设为0
                updateTimeDisplay();
            });
            
            video.addEventListener('timeupdate', function() {
                currentTime = video.currentTime;
                updateProgress();
                updateTimeDisplay();
                
                // 每5秒保存一次观看进度
                if (currentVideo && Math.floor(currentTime) % 5 === 0) {
                    const progress = totalTime > 0 ? (currentTime / totalTime) * 100 : 0;
                    saveVideoWatchProgress(currentVideo.id, progress);
                }
            });
            
            video.addEventListener('play', function() {
                isPlaying = true;
                watchStartTime = Date.now();
                // 开始学习记录
                startLearning();
            });
            
            video.addEventListener('pause', function() {
                isPlaying = false;
                // 记录观看时长
                recordWatchDuration();
            });
            
            video.addEventListener('ended', function() {
                console.log('视频播放结束事件触发');
                isPlaying = false;
                
                // 延迟执行API调用，避免与视频解码冲突
                setTimeout(() => {
                    try {
                        // 记录观看时长和学习进度
                        recordWatchDuration();
                        completeLearning();
                    } catch (error) {
                        console.error('视频播放结束后的处理出错:', error);
                    }
                }, 100); // 延迟100ms执行
            });
            
            // 添加错误处理
            video.addEventListener('error', function(e) {
                console.error('视频播放错误:', e);
                console.error('错误详情:', {
                    error: video.error,
                    networkState: video.networkState,
                    readyState: video.readyState,
                    src: video.src,
                    currentSrc: video.currentSrc
                });
                
                let errorMessage = '视频播放失败';
                let errorDetail = '请检查网络连接或联系管理员';
                
                if (video.error) {
                    switch (video.error.code) {
                        case 1:
                            errorMessage = '视频加载被中止';
                            errorDetail = '网络连接中断或服务器响应超时';
                            break;
                        case 2:
                            errorMessage = '网络错误';
                            errorDetail = '无法连接到视频服务器';
                            break;
                        case 3:
                            errorMessage = '视频解码错误';
                            errorDetail = '视频格式不支持或文件损坏';
                            // 如果是播放结束后的解码错误，可能是正常的
                            if (video.currentTime > 0 && video.duration > 0 && 
                                Math.abs(video.currentTime - video.duration) < 1) {
                                console.log('检测到播放结束后的解码错误，可能是正常的');
                                errorMessage = '视频播放完成';
                                errorDetail = '视频已播放完毕';
                                // 不显示错误界面，直接返回
                                return;
                            }
                            break;
                        case 4:
                            errorMessage = '视频格式不支持';
                            errorDetail = '浏览器不支持此视频格式';
                            break;
                        default:
                            errorMessage = '未知播放错误';
                            errorDetail = `错误代码: ${video.error.code}`;
                    }
                }
                
                playerContainer.innerHTML = `
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666;">
                        <i style="font-size: 48px; margin-bottom: 16px;">⚠️</i>
                        <h3>${errorMessage}</h3>
                        <p>${errorDetail}</p>
                        <div style="margin-top: 16px; display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="location.reload()">重新加载</button>
                            <button class="btn btn-secondary" onclick="window.history.back()">返回</button>
                        </div>
                    </div>
                `;
            });
            
            // 添加加载事件监听器
            video.addEventListener('loadstart', function() {
                console.log('开始加载视频:', video.src);
            });
            
            video.addEventListener('loadedmetadata', function() {
                console.log('视频元数据加载完成');
            });
            
            video.addEventListener('canplay', function() {
                console.log('视频可以开始播放');
            });
            
            video.addEventListener('canplaythrough', function() {
                console.log('视频可以流畅播放');
            });
        }

        // 更新进度条
        function updateProgress() {
            if (totalTime > 0) {
                const progress = (currentTime / totalTime) * 100;
                document.getElementById('progressFill').style.width = progress + '%';
            }
        }

        // 更新时间显示
        function updateTimeDisplay() {
            document.getElementById('currentTime').textContent = Utils.formatDuration(currentTime);
            document.getElementById('totalTime').textContent = Utils.formatDuration(totalTime);
        }

        // 跳转到指定时间
        function seekTo(event) {
            if (!videoPlayer || totalTime === 0) return;
            
            const progressBar = document.getElementById('progressBar');
            const rect = progressBar.getBoundingClientRect();
            const clickX = event.clientX - rect.left;
            const percentage = clickX / rect.width;
            const newTime = percentage * totalTime;
            
            videoPlayer.currentTime = newTime;
        }

        // 加载相关视频
        async function loadRelatedVideos() {
            const container = document.getElementById('playlistContent');
            
            try {
                // 显示加载状态
                container.innerHTML = `
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #666;">
                        <div class="loading-pulse" style="margin-bottom: 12px;"></div>
                        <p style="font-size: 12px;">加载相关视频...</p>
                    </div>
                `;

                console.log('正在请求视频列表...');
                const response = await API.get('/video/all');
                console.log('视频列表响应:', response);
                if (response.success) {
                    const videos = response.videos || [];
                    const relatedVideos = videos.filter(v => v.id !== currentVideo.id).slice(0, 5);
                    
                    if (relatedVideos.length === 0) {
                        container.innerHTML = `
                            <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #666;">
                                <div style="font-size: 24px; margin-bottom: 8px;">📺</div>
                                <p>暂无相关视频</p>
                            </div>
                        `;
                        return;
                    }
                    
                    container.innerHTML = relatedVideos.map(video => {
                        const watchProgress = getVideoWatchProgress(video.id);
                        const isWatched = watchProgress >= 90; // 观看90%以上算已观看
                        const isCurrentVideo = video.id === currentVideo.id;
                        
                        return `
                            <div class="playlist-item ${isCurrentVideo ? 'active' : ''} ${isWatched ? 'watched' : ''}" 
                                 onclick="playVideo(${video.id})">
                                <div class="playlist-thumbnail">🎬</div>
                                <div class="playlist-info">
                                    <h4>${video.title || '未命名视频'}</h4>
                                    <div class="playlist-meta">${video.uploaderName || '未知老师'}</div>
                                    ${watchProgress > 0 ? `
                                        <div class="playlist-progress">
                                            <div class="playlist-progress-bar" style="width: ${watchProgress}%"></div>
                                        </div>
                                        <div class="playlist-stats">
                                            <span class="playlist-watch-time">已观看 ${Math.round(watchProgress)}%</span>
                                        </div>
                                    ` : ''}
                                </div>
                                <div class="playlist-duration">--:--</div>
                            </div>
                        `;
                    }).join('');
                } else {
                    // API返回失败
                    container.innerHTML = `
                        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #dc3545;">
                            <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>
                            <p>加载视频列表失败</p>
                            <p style="font-size: 12px; margin-top: 4px;">${response.message || '请稍后重试'}</p>
                            <button onclick="loadRelatedVideos()" style="margin-top: 8px; padding: 4px 8px; font-size: 12px; background: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
                                重新加载
                            </button>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载相关视频失败:', error);
                
                // 尝试备用方案：从播放列表获取视频
                try {
                    console.log('尝试备用方案：从播放列表获取视频...');
                    await loadVideosFromPlaylist();
                } catch (backupError) {
                    console.error('备用方案也失败:', backupError);
                    container.innerHTML = `
                        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #dc3545;">
                            <div style="font-size: 24px; margin-bottom: 8px;">❌</div>
                            <p>加载视频列表失败</p>
                            <p style="font-size: 12px; margin-top: 4px;">网络连接异常，请检查网络后重试</p>
                            <button onclick="loadRelatedVideos()" style="margin-top: 8px; padding: 4px 8px; font-size: 12px; background: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
                                重新加载
                            </button>
                        </div>
                    `;
                }
            }
        }

        // 备用方案：从播放列表获取视频
        async function loadVideosFromPlaylist() {
            const container = document.getElementById('playlistContent');
            
            try {
                // 尝试获取用户的播放列表
                const userId = UserManager.getUserId();
                if (!userId) {
                    throw new Error('用户未登录');
                }
                
                const response = await API.get(`/playlist/user/${userId}`);
                if (response.success && response.playlists && response.playlists.length > 0) {
                    // 从第一个播放列表获取视频
                    const firstPlaylist = response.playlists[0];
                    const videosResponse = await API.get(`/playlist/${firstPlaylist.id}/videos`);
                    
                    if (videosResponse.success && videosResponse.videos) {
                        const videos = videosResponse.videos.filter(v => v.id !== currentVideo.id).slice(0, 5);
                        
                        if (videos.length === 0) {
                            container.innerHTML = `
                                <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; color: #666;">
                                    <div style="font-size: 24px; margin-bottom: 8px;">📺</div>
                                    <p>播放列表中暂无其他视频</p>
                                </div>
                            `;
                            return;
                        }
                        
                        container.innerHTML = videos.map(video => {
                            const watchProgress = getVideoWatchProgress(video.videoId);
                            const isWatched = watchProgress >= 90;
                            const isCurrentVideo = video.videoId === currentVideo.id;
                            
                            return `
                                <div class="playlist-item ${isCurrentVideo ? 'active' : ''} ${isWatched ? 'watched' : ''}" 
                                     onclick="playVideo(${video.videoId})">
                                    <div class="playlist-thumbnail">🎬</div>
                                    <div class="playlist-info">
                                        <h4>${video.videoTitle || '未命名视频'}</h4>
                                        <div class="playlist-meta">${video.uploaderName || '未知老师'}</div>
                                        ${watchProgress > 0 ? `
                                            <div class="playlist-progress">
                                                <div class="playlist-progress-bar" style="width: ${watchProgress}%"></div>
                                            </div>
                                            <div class="playlist-stats">
                                                <span class="playlist-watch-time">已观看 ${Math.round(watchProgress)}%</span>
                                            </div>
                                        ` : ''}
                                    </div>
                                    <div class="playlist-duration">--:--</div>
                                </div>
                            `;
                        }).join('');
                    } else {
                        throw new Error('无法获取播放列表视频');
                    }
                } else {
                    throw new Error('没有找到播放列表');
                }
            } catch (error) {
                console.error('备用方案失败:', error);
                throw error;
            }
        }

        // 播放视频
        function playVideo(videoId) {
            window.location.href = `player.html?id=${videoId}`;
        }

        // 获取视频观看进度
        function getVideoWatchProgress(videoId) {
            try {
                const watchData = localStorage.getItem(`video_watch_${videoId}`);
                if (watchData) {
                    const data = JSON.parse(watchData);
                    return data.progress || 0;
                }
            } catch (error) {
                console.error('获取观看进度失败:', error);
            }
            return 0;
        }

        // 保存视频观看进度
        function saveVideoWatchProgress(videoId, progress) {
            try {
                const watchData = {
                    videoId: videoId,
                    progress: progress,
                    lastWatchTime: new Date().toISOString()
                };
                localStorage.setItem(`video_watch_${videoId}`, JSON.stringify(watchData));
            } catch (error) {
                console.error('保存观看进度失败:', error);
            }
        }

        // 加载笔记
        async function loadNotes() {
            if (!currentVideo || !UserManager.isLoggedIn()) return;
            
            try {
                const userId = UserManager.getUserId();
                const response = await API.get(`/note/user/${userId}/video/${currentVideo.id}`);
                
                const container = document.getElementById('notesList');
                if (response.success && response.notes && response.notes.length > 0) {
                    container.innerHTML = response.notes.map(note => `
                        <div class="note-item" data-note-id="${note.id}">
                            <div class="note-header">
                                <div class="note-time">${Utils.formatTime(note.createdTime)}</div>
                                <div class="note-actions">
                                    <button class="note-edit-btn" onclick="editNote(${note.id})">编辑</button>
                                    <button class="note-delete-btn" onclick="deleteNote(${note.id})">删除</button>
                                </div>
                            </div>
                            <div class="note-title">${note.title}</div>
                            <div class="note-content">${note.content}</div>
                            ${note.position > 0 ? `<div class="note-position">位置: ${Utils.formatDuration(note.position)}</div>` : ''}
                        </div>
                    `).join('');
                } else {
                    container.innerHTML = '<div class="no-notes">暂无笔记</div>';
                }
            } catch (error) {
                console.error('加载笔记失败:', error);
                const container = document.getElementById('notesList');
                container.innerHTML = '<div class="no-notes">加载笔记失败</div>';
            }
        }

        // 保存笔记
        async function saveNote() {
            if (!currentVideo || !UserManager.isLoggedIn()) {
                Message.error('请先登录');
                return;
            }
            
            const noteInput = document.getElementById('noteInput');
            const content = noteInput.value.trim();
            
            if (!content) {
                Message.warning('请输入笔记内容');
                return;
            }
            
            try {
                const response = await API.post('/note/save', {
                    videoId: currentVideo.id,
                    title: `笔记 ${Utils.formatTime(new Date())}`,
                    content: content,
                    position: Math.floor(currentTime)
                });
                
                if (response.success) {
                    // 清空输入框
                    noteInput.value = '';
                    // 重新加载笔记列表
                    loadNotes();
                    Message.success('笔记保存成功');
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('保存笔记失败:', error);
                Message.error('保存笔记失败，请稍后重试');
            }
        }

        // 编辑笔记
        async function editNote(noteId) {
            try {
                const response = await API.get(`/note/${noteId}`);
                if (response.success) {
                    const note = response.note;
                    const newTitle = prompt('编辑笔记标题:', note.title);
                    if (newTitle === null) return;
                    
                    const newContent = prompt('编辑笔记内容:', note.content);
                    if (newContent === null) return;
                    
                    const updateResponse = await API.put('/note/update', {
                        id: noteId,
                        title: newTitle,
                        content: newContent,
                        position: note.position
                    });
                    
                    if (updateResponse.success) {
                        loadNotes();
                        Message.success('笔记更新成功');
                    } else {
                        Message.error(updateResponse.message);
                    }
                }
            } catch (error) {
                console.error('编辑笔记失败:', error);
                Message.error('编辑笔记失败');
            }
        }

        // 删除笔记
        async function deleteNote(noteId) {
            if (!confirm('确定要删除这条笔记吗？')) return;
            
            try {
                const response = await API.delete(`/note/${noteId}`);
                if (response.success) {
                    loadNotes();
                    Message.success('笔记删除成功');
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('删除笔记失败:', error);
                Message.error('删除笔记失败');
            }
        }


        // 添加到播放列表
        async function addToPlaylist() {
            if (!currentVideo || !UserManager.isLoggedIn()) {
                Message.error('请先登录');
                return;
            }
            
            try {
                // 获取用户的播放列表
                const userId = UserManager.getUserId();
                const response = await API.get(`/playlist/user/${userId}`);
                
                if (response.success && response.playlists && response.playlists.length > 0) {
                    // 显示播放列表选择对话框
                    showPlaylistSelector(response.playlists);
                } else {
                    // 没有播放列表，提示创建
                    if (confirm('您还没有播放列表，是否要创建一个？')) {
                        window.location.href = 'playlists.html';
                    }
                }
            } catch (error) {
                console.error('获取播放列表失败:', error);
                Message.error('获取播放列表失败');
            }
        }

        // 显示播放列表选择器
        function showPlaylistSelector(playlists) {
            const playlistNames = playlists.map(p => p.name);
            const selectedIndex = prompt(`选择要添加到的播放列表:\n${playlistNames.map((name, index) => `${index + 1}. ${name}`).join('\n')}\n\n请输入播放列表编号:`);
            
            if (selectedIndex === null) return;
            
            const index = parseInt(selectedIndex) - 1;
            if (index >= 0 && index < playlists.length) {
                const selectedPlaylist = playlists[index];
                addVideoToPlaylist(selectedPlaylist.id);
            } else {
                Message.warning('无效的播放列表编号');
            }
        }

        // 添加视频到播放列表
        async function addVideoToPlaylist(playlistId) {
            try {
                const response = await API.post(`/playlist/${playlistId}/add-video`, {
                    videoId: currentVideo.id
                });
                
                if (response.success) {
                    Message.success(response.message);
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('添加视频到播放列表失败:', error);
                Message.error('添加失败，请稍后重试');
            }
        }

        // 分享视频
        function shareVideo() {
            const url = window.location.href;
            Utils.copyToClipboard(url).then(() => {
                Message.success('视频链接已复制到剪贴板');
            }).catch(() => {
                Message.error('复制失败，请手动复制链接');
            });
        }

        // 记录学习进度
        function recordProgress() {
            try {
                // 这里可以调用API记录学习进度
                console.log('记录学习进度:', {
                    videoId: currentVideo.id,
                    progress: (currentTime / totalTime) * 100,
                    completed: currentTime >= totalTime * 0.9 // 观看90%以上算完成
                });
            } catch (error) {
                console.error('记录学习进度失败:', error);
            }
        }

        // 检查收藏状态
        async function checkFavoriteStatus() {
            if (!currentVideo || !UserManager.isLoggedIn()) return;
            
            try {
                const response = await API.get(`/favorite/check/${currentVideo.id}`);
                if (response.success) {
                    isFavorited = response.isFavorited;
                    updateFavoriteButton();
                }
            } catch (error) {
                console.error('检查收藏状态失败:', error);
            }
        }

        // 更新收藏按钮状态
        function updateFavoriteButton() {
            const btn = document.getElementById('favoriteBtn');
            if (isFavorited) {
                btn.classList.add('favorited');
                btn.innerHTML = '❤️ 已收藏';
            } else {
                btn.classList.remove('favorited');
                btn.innerHTML = '❤️ 收藏';
            }
        }

        // 切换收藏状态
        async function toggleFavorite() {
            if (!currentVideo || !UserManager.isLoggedIn()) {
                Message.error('请先登录');
                return;
            }
            
            try {
                const response = await API.post('/favorite/toggle', {
                    videoId: currentVideo.id
                });
                
                if (response.success) {
                    isFavorited = response.isFavorited;
                    updateFavoriteButton();
                    Message.success(response.message);
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('切换收藏状态失败:', error);
                Message.error('操作失败，请稍后重试');
            }
        }

        // 开始学习
        async function startLearning() {
            if (!currentVideo || !UserManager.isLoggedIn()) return;
            
            try {
                await API.post('/learning/start', {
                    videoId: currentVideo.id
                });
            } catch (error) {
                console.error('开始学习记录失败:', error);
            }
        }

        // 记录观看时长
        async function recordWatchDuration() {
            if (!currentVideo || !UserManager.isLoggedIn() || !watchStartTime) {
                console.log('跳过观看时长记录:', {
                    hasVideo: !!currentVideo,
                    isLoggedIn: UserManager.isLoggedIn(),
                    hasStartTime: !!watchStartTime
                });
                return;
            }
            
            const duration = Math.floor((Date.now() - watchStartTime) / 1000);
            totalWatchDuration += duration;
            watchStartTime = null;
            
            console.log('记录观看时长:', {
                videoId: currentVideo.id,
                duration: duration,
                totalDuration: totalWatchDuration
            });
            
            try {
                const response = await API.post('/video-view/record', {
                    videoId: currentVideo.id,
                    watchDuration: duration
                });
                
                if (response.success) {
                    console.log('观看时长记录成功:', response.message);
                } else {
                    console.warn('观看时长记录失败:', response.message);
                }
            } catch (error) {
                console.error('记录观看时长API调用失败:', error);
                // 不显示错误给用户，因为这不是关键功能
            }
        }

        // 更新学习进度
        async function updateLearningProgress() {
            if (!currentVideo || !UserManager.isLoggedIn() || !totalTime) return;
            
            try {
                const progress = Math.min((currentTime / totalTime) * 100, 100);
                await API.post('/learning/progress', {
                    videoId: currentVideo.id,
                    duration: Math.floor(currentTime),
                    currentPosition: Math.floor(currentTime),
                    totalDuration: Math.floor(totalTime)
                });
            } catch (error) {
                console.error('更新学习进度失败:', error);
            }
        }

        // 完成学习
        async function completeLearning() {
            if (!currentVideo || !UserManager.isLoggedIn()) {
                console.log('跳过学习完成记录:', {
                    hasVideo: !!currentVideo,
                    isLoggedIn: UserManager.isLoggedIn()
                });
                return;
            }
            
            console.log('完成学习记录:', {
                videoId: currentVideo.id,
                videoTitle: currentVideo.title
            });
            
            try {
                const response = await API.post('/learning/complete', {
                    videoId: currentVideo.id
                });
                
                if (response.success) {
                    console.log('学习完成记录成功:', response.message);
                    Message.success('恭喜完成学习！');
                } else {
                    console.warn('学习完成记录失败:', response.message);
                    // 不显示错误给用户，因为这不是关键功能
                }
            } catch (error) {
                console.error('完成学习记录API调用失败:', error);
                // 不显示错误给用户，因为这不是关键功能
            }
        }

        // 加载学习记录
        async function loadLearningRecord() {
            if (!currentVideo || !UserManager.isLoggedIn()) return;
            
            try {
                const userId = UserManager.getUserId();
                const response = await API.get(`/learning/user/${userId}/video/${currentVideo.id}`);
                if (response.success && response.record) {
                    learningRecord = response.record;
                    // 如果有学习记录，可以恢复播放位置
                    if (learningRecord.lastPosition > 0) {
                        setTimeout(() => {
                            if (videoPlayer && learningRecord.lastPosition < totalTime) {
                                videoPlayer.currentTime = learningRecord.lastPosition;
                            }
                        }, 1000);
                    }
                }
            } catch (error) {
                console.error('加载学习记录失败:', error);
            }
        }

        // 显示错误信息
        function showError(message) {
            const container = document.getElementById('videoPlayer');
            container.innerHTML = `
                <div class="error-message">
                    <i>❌</i>
                    <p>${message}</p>
                    <a href="index.html" class="btn btn-primary">返回首页</a>
                </div>
            `;
        }

        // 退出登录
        async function logout() {
            try {
                await API.post('/user/logout');
                sessionStorage.removeItem('user');
                window.location.href = '../login.html';
            } catch (error) {
                console.error('退出登录失败:', error);
                Message.error('退出登录失败');
            }
        }
    </script>
</body>
</html>
